package com.humngyang.com.hmy.study.concurrency.myannoations.aqs;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

public class ForkJoinTaskExample extends RecursiveTask<Integer> {

    private static Logger log = LoggerFactory.getLogger(ForkJoinTaskExample.class);

    public static final int threshold = 2;
    private int start;
    private int end;

    public ForkJoinTaskExample(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        //如果任务足够小的话，就计算
        boolean canCompute = (end - start) <= threshold;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            //如果任务大于与之，就分裂成两个子任务计算
            int middle = (start + end) / 2;
            ForkJoinTaskExample leftTask1 = new ForkJoinTaskExample(start, middle);
            ForkJoinTaskExample leftTask2 = new ForkJoinTaskExample(middle+1, end);
            //执行子任务
            leftTask1.fork();
            leftTask2.fork();
            //等待任务执行结束合并其结果
            int leftresult = leftTask1.join();
            int leftresult2 = leftTask2.join();
            //合并子任务
            sum = leftresult + leftresult2;
        }
        return sum;
    }
    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        // 生成计算任务，计算1+2+3+4
        ForkJoinTaskExample task = new ForkJoinTaskExample(1, 100);
        //执行一个任务
        Future<Integer> result = forkJoinPool.submit(task);

        try {
            log.info("result :{}", result.get());
        } catch (Exception e) {
            log.error("excpetion", e);
        }
    }
}
